import threading
import os
import logging
import StringIO
import properties
from utils.image_info import ImageConvertInfo


# descriptors ?! for logging


class PyIPS(object):
    
    def __init__(self):
	self.log = logging.getLogger("pyips")
	handler = logging.FileHandler(properties.log_file)
	formatter = logging.Formatter('%(asctime)s %(levelname)5s %(message)s')
	handler.setFormatter(formatter)
	self.log.addHandler(handler)
	self.log.setLevel(properties.log_level)
	
	semaphore = threading.BoundedSemaphore()
	
	init_engines()
		

    def init_engines(self):
	for file_name in os.dirlist(properties.engines):
	    print "engine", file_name

    def process_request(query_values):
	log.info("Request received")
    
	if query_values == []:
	    log.error("No query in url")
	    return "No params in query", "text/plain"
    
	info = ImageConvertInfo()
    
	for (name, value) in query_values:
	    if name in dir(info):
		setattr(info, name, value)
		log.info("setting %s to %s" % (name, value))
	    #if name == 'name':
	    #    info.name = value
    	    #elif name == 'width':
	    #    info.width = value
	    #elif name == 
	log.info("New info created: %s" % str(info))
	
	log.info("Acquiring a semaphore (%d free slots)" % semaphore._Semaphore__value)
	semaphore.acquire()            # decrements the counter

	try:
	    result, img_type = process_image(info)
	finally:
	    semaphore.release()
	log.info("The semaphore released (%d free slots)" % semaphore._Semaphore__value)
	
	return result, str("image/" + img_type)
    
  
def process_image(info):
    
    if not isinstance(info, ImageConvertInfo):
        raise Exception
    
    width = info.width
    height = info.height
    
    log.info("Is width is int? " + str(isinstance(width, int)))
    
    if not width and not height:
        log.info("No processing - just return original")
        return None
    
    full_image_name = os.path.join(home_dir, info.name)

    image = engine.read_image(full_image_name)
    
    if not info.requested_image_type:
	info.requested_image_type = image.format
    
    image = engine.scale_image(image, width, height, info.crop_type, info.scale_up_allowed)
    engine.save_image(image, os.path.join(home_dir, generate_image_name(info)), info.requested_image_type)

    log.info("Done")
    #image_file = filestorage.getFile(info.image_name)
    
    #if not image_file:
	#print "No image file"
	#return None
    #log.info(image.tostring())
    some = StringIO.StringIO()
    image.save(some, info.requested_image_type)
    return some.getvalue(), info.requested_image_type
	
	
def generate_image_name(info):
    name = info.name
    paramslist = []

    paramslist.append(str(info.width) + "x" + str(info.height))
    
    if not info.crop_type:
	paramslist.append("uncropped")
    else:
	paramslist.append(info.crop_type + "cropped")
	
    if info.background_color:
	paramslist.append("background" + info.background_color)
	
    name += "(" + "-".join(paramslist) + ")"
    return name
    
    
if __name__ == "__main__":
    PyIPS()